//
//  CXGCDTimer.m
//  JwPackDemo
//
//  Created by 陈警卫 on 2025/8/15.
//

#import "CXGCDTimer.h"

@interface CXGCDTimer ()

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) BOOL isSuspend;

@end

@implementation CXGCDTimer

/// 初始化计时器
/// 默认 global队列 100ms容差
+ (CXGCDTimer *)startWithInterval:(NSTimeInterval)interval handler:(dispatch_block_t)handler {
    return [self startWithInterval:interval queue:nil leeway:0.1 handler:handler];
}

/// 初始化计时器
/// queue 计时器队列
/// leeway 容差值(单位s)
+ (CXGCDTimer *)startWithInterval:(NSTimeInterval)interval
                            queue:(dispatch_queue_t)queue
                           leeway:(CGFloat)leeway
                          handler:(dispatch_block_t)handler {
    CXGCDTimer *timer = [[CXGCDTimer alloc] init];
    [timer startWithInterval:interval queue:queue leeway:leeway handler:handler];
    return timer;
}

/// 初始化计时器
/// 默认 global队列 100ms容差
- (void)startWithInterval:(NSTimeInterval)interval handler:(dispatch_block_t)handler {
    [self startWithInterval:interval queue:nil leeway:0.1 handler:handler];
}

/// 初始化计时器
/// queue 计时器队列
/// leeway 容差值(单位s)
- (void)startWithInterval:(NSTimeInterval)interval queue:(dispatch_queue_t)queue leeway:(CGFloat)leeway handler:(dispatch_block_t)handler {
    
    if (!queue) {
        queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    }
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(self.timer,
                              dispatch_time(DISPATCH_TIME_NOW, 0),
                              (uint64_t)(interval * NSEC_PER_SEC),
                              (uint64_t)(leeway * NSEC_PER_SEC));
    
    dispatch_source_set_event_handler(self.timer, handler);
    dispatch_activate(self.timer);
    self.isSuspend = NO;
}

/// 暂停计时器
- (void)pause {
    if (!self.timer || self.isSuspend) {
        return;
    }
    dispatch_suspend(self.timer);
    self.isSuspend = YES;
}

/// 恢复计时器
- (void)resume {
    if (!self.timer || !self.isSuspend) {
        return;
    }
    dispatch_resume(self.timer);
    self.isSuspend = NO;
}

/// 停止销毁计时器
- (void)stop {
    if (!self.timer) {
        return;
    }
    if (self.isSuspend) {
        // 恢复再取消，避免崩溃
        [self resume];
    }
    dispatch_source_cancel(self.timer);
    self.timer = nil;
}


@end
